package tester.input;

import messages.MessageTypeNotFoundException;
import messages.MessageUtils;
import state.Globals;

/**
 * This class will create TesterMessagesd
 * @author Caleb Chan
 *
 */
public class TesterMessageFactory {

	/**
	 * This method will convert a byte array into the appropriate TesterMessage
	 * @param data The data to be converted
	 * @return Returns the converted TesterMessage
	 */
	public static TesterMessage parseMessage(byte[] data){
		if(data == null || data.length == 0){
			return null;
		}
		
		// Retreives the tester message type
		TesterMessageType type = TesterMessageType.getMessageTypeForId(data[0]);
		
		if (type == null){
			return null;
		}
		
		// Returns the appropriate message depending on the type
		try{
			switch(type){
			case CreateElevatorMessage:
				return new CreateElevatorMessage();
			case CreateDelayMessage:
				return new CreateDelayMessage(data);
			case DestroyElevatorMessage:
				return new DestroyElevatorMessage(data);
			default:
                throw new MessageTypeNotFoundException();
			}
		}catch(RuntimeException e){
            if (e.getClass().getName().equals("java.lang.RuntimeException")){
            	Globals.getLogger().log("Received an invalid message with data: " + MessageUtils.byteArrayToString(data));
                return null;
            }
            else{
                throw (e);
            }			
		}
	}
}
